package com.gao.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gao.dao.OrderProductDao;
import com.gao.domain.Order;
import com.gao.domain.OrderProduct;
import com.gao.util.DBUtil;

public class OrderProductDaoImpl implements OrderProductDao{

	@Override
	public boolean insert(OrderProduct orderProduct) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "insert into order_product values(null,?,?,?,?,?,now())";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, orderProduct.getOrder().getOid());
		pstmt.setInt(2, orderProduct.getPid());
		pstmt.setString(3, orderProduct.getPname());
		pstmt.setDouble(4, orderProduct.getPrice());
		pstmt.setInt(5, orderProduct.getCartNum());
		int num = pstmt.executeUpdate();
		DBUtil.release(pstmt, conn);
		return num>0;
	}

	@Override
	public List<OrderProduct> findByOid(String oid) throws SQLException {
		List<OrderProduct> orderProducts = new ArrayList<OrderProduct>();
		OrderProduct orderProduct = null;
		Connection conn = DBUtil.getConnection();
		String sql = "select * from order_product where oid=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, oid);
		ResultSet rs = pstmt.executeQuery();
		while(rs.next()){
			orderProduct = new OrderProduct(rs.getInt(1),new Order(oid),rs.getInt(3),rs.getString(4),rs.getDouble(5),rs.getInt(6),rs.getTimestamp(7));
			orderProducts.add(orderProduct);
		}
		DBUtil.release(rs,pstmt, conn);
		return orderProducts;
	}

}
